import React, { useState, useEffect } from 'react';
import { Editor } from '@tiptap/react';

interface FindReplaceButtonProps {
  editor: Editor;
  icon: string;
  title?: string;
}

const FindReplaceButton: React.FC<FindReplaceButtonProps> = ({
  editor,
  icon,
  title = '查找替换'
}) => {
  const [showPanel, setShowPanel] = useState(false);
  const [findText, setFindText] = useState('');
  const [replaceText, setReplaceText] = useState('');

  // 添加清除高亮的方法
  const clearHighlights = () => {
    editor.chain()
      .focus()
      .selectAll()
      .unsetHighlight()
      .blur()
      .run();
  };

  const handleFind = () => {
    if (!findText) return;
    
    // 先清除之前的高亮
    clearHighlights();
    
    const text = editor.state.doc.textContent;
    const regex = new RegExp(findText, 'g');
    const matches = text.match(regex);

    // 添加新的高亮，只高亮匹配的文本
    editor.state.doc.descendants((node, pos) => {
      if (node.isText) {
        const text = node.text || '';
        let match;
        regex.lastIndex = 0;

        while ((match = regex.exec(text)) !== null) {
          const from = pos + match.index;
          const to = from + match[0].length;

          editor.chain()
            .focus()
            .setTextSelection({ from, to })
            .setHighlight({ color: '#ffeb3b' })
            .run();
        }
      }
    });

    if (!matches?.length) {
      alert('未找到匹配内容');
    } else {
      alert(`找到 ${matches.length} 处匹配`);
    }
  };

  // 添加监听面板状态的 useEffect
  useEffect(() => {
    if (!showPanel) {
      clearHighlights();
      setFindText(''); 
      setReplaceText('')
    }
  }, [showPanel]);

  const handleReplace = () => {
    if (!findText) return;
  
    let replaceCount = 0;
    const regex = new RegExp(findText, 'g');
    
    // 遍历文档中的每个文本节点
    editor.state.doc.descendants((node, pos) => {
      if (node.isText) {
        const text = node.text || '';
        let match;
        regex.lastIndex = 0;
  
        // 查找匹配的文本
        while ((match = regex.exec(text)) !== null) {
          const from = pos + match.index;
          const to = from + match[0].length;
          
          // 替换匹配的文本
          editor.chain()
            .focus()
            .setTextSelection({ from, to })
            .insertContent(replaceText)
            .run();
  
          replaceCount++;
        }
      }
    });
  
    if (replaceCount > 0) {
      alert(`已替换 ${replaceCount} 处内容`);
    }
    setShowPanel(false);
  };


  // 点击外部关闭面板
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.find-replace-container')) {
        setShowPanel(false);
      }
    };

    if (showPanel) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showPanel]);

  return (
    <div className="find-replace-container">
      <button
        onClick={() => setShowPanel(!showPanel)}
        className={`toolbar-button ${showPanel ? 'is-active' : ''}`}
        title={title}
      >
        <i className="icon">{icon}</i>
      </button>

      {showPanel && (
        <div className="find-replace-panel">
          <div className="find-replace-row">
            <input
              type="text"
              placeholder="查找"
              value={findText}
              onChange={(e) => setFindText(e.target.value)}
            />
            <button onClick={handleFind}>查找</button>
          </div>
          <div className="find-replace-row">
            <input
              type="text"
              placeholder="替换"
              value={replaceText}
              onChange={(e) => setReplaceText(e.target.value)}
            />
            <button onClick={handleReplace}>替换全部</button>
          </div>
        </div>
      )}
    </div>
  );
};

export default FindReplaceButton;